package com.wn.main.ui.system

import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ConvertUtils
import com.wn.framework.base.BaseFragment
import com.wn.framework.decoration.NormalItemDecoration
import com.wn.main.R
import com.wn.main.databinding.FragmentSystemBinding
import com.wn.main.ui.system.adapter.SystemAdapter
import com.wn.main.ui.system.viewmodel.SystemViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @Author: wn
 * @Date: 2025/4/28 15:44
 * @Description: 体系 页面 -- 列表 嵌套 列表
 */
@AndroidEntryPoint
class SystemFragment : BaseFragment<FragmentSystemBinding>() {

  override fun getLayoutRes() = R.layout.fragment_system

  private val viewModel by viewModels<SystemViewModel>()

  @Inject
  lateinit var systemAdapter: SystemAdapter

  @Inject
  lateinit var normalItemDecoration: NormalItemDecoration

  override fun initView() {
    mBinding.recyclerView.apply {
      layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
      adapter = systemAdapter
      addItemDecoration(normalItemDecoration.apply {
        setLastBottom(true)
        setBounds(
          ConvertUtils.dp2px(8.0F),
          ConvertUtils.dp2px(10.0F),
          ConvertUtils.dp2px(8.0F),
          ConvertUtils.dp2px(10.0F)
        )
      })
    }
  }

  private lateinit var job: Job
  override fun initData() {
    if (::job.isInitialized) job.cancel()

    job = lifecycleScope.launch {
      lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
        // 获取体系列表
        launch {
          viewModel.getSystemList().collect {
            // 空 骨架屏
            mBinding.viewEmptyData.isVisible = it.isNullOrEmpty()
            it ?: return@collect
            systemAdapter.setData(it)
          }
        }
        // 加载 loading
        launch {
          // delay(20) // 确保 loading 先为 true-->控制 刷新
          viewModel.loading.collect {
            if (it) showLoading() else dismissLoading()
          }
        }
      }
    }
  }

  /**
   * Home键或者锁屏 后 如果不 cancel 返回时数据会重复请求  -- stop
   * viewPager 滑动 -- pause
   */
  override fun onStop() {
    if (::job.isInitialized) job.cancel()
    super.onStop()
  }
}